import { getRecipes, getRecipeDetail } from '@/api/recipes'

export default {
  namespaced: true,
  
  state: {
    recipes: [],
    currentRecipe: null,
    total: 0,
    loading: false
  },

  mutations: {
    SET_RECIPES(state, { list, total }) {
      state.recipes = list
      state.total = total
    },
    SET_CURRENT_RECIPE(state, recipe) {
      state.currentRecipe = recipe
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    UPDATE_FAVORITE_STATUS(state, { recipeId, isFavorite }) {
      const recipe = state.recipes.find(r => r.id === recipeId)
      if (recipe) {
        recipe.isFavorite = isFavorite
      }
    }
  },

  actions: {
    async getRecipes({ commit }, params = {}) {
      try {
        commit('SET_LOADING', true)
        const res = await getRecipes(params)
        if (res.code === 200 && res.data) {
          commit('SET_RECIPES', {
            list: res.data.list,
            total: res.data.total
          })
          return res.data
        }
        throw new Error(res.message || '获取食谱列表失败')
      } catch (error) {
        console.error('获取食谱列表失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    async getRecipeDetail({ commit }, id) {
      try {
        commit('SET_LOADING', true)
        const res = await getRecipeDetail(id)
        if (res.code === 200 && res.data) {
          commit('SET_CURRENT_RECIPE', res.data)
          return res.data
        }
        throw new Error(res.message || '获取食谱详情失败')
      } catch (error) {
        console.error('获取食谱详情失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    updateFavoriteStatus({ commit }, { recipeId, isFavorite }) {
      commit('UPDATE_FAVORITE_STATUS', { recipeId, isFavorite })
    }
  }
} 